package com.yikaiye.android.yikaiye.ui.activity.service;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.base.BaseActivity;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.ActivityServiceDetailsBinding;
import com.yikaiye.android.yikaiye.model.EventBusModel;
import com.yikaiye.android.yikaiye.ui.activity.mine.CompanyDetailsActivity;
import com.yikaiye.android.yikaiye.ui.activity.order.OrderDetailsActivity;
import com.yikaiye.android.yikaiye.ui.activity.service.viewmodel.ServiceDetailsViewModel;
import com.yikaiye.android.yikaiye.ui.adapter.AttrAdapter;
import com.yikaiye.android.yikaiye.ui.adapter.ViewPagerAdapter;
import com.yikaiye.android.yikaiye.ui.fragment.CorrelationServiceFragment;
import com.yikaiye.android.yikaiye.ui.fragment.ServiceDescriptionFragment;
import com.yikaiye.android.yikaiye.ui.fragment.ServiceProgressFragment;
import com.yikaiye.android.yikaiye.utils.CommonUtil;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.ToastHelper;
import com.yikaiye.android.yikaiye.utils.UiUtils;
import com.yikaiye.android.yikaiye.widget.flowLayout.FlowLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务详情
 */
public class ServiceDetailsActivity extends BaseActivity<ActivityServiceDetailsBinding, ServiceDetailsViewModel> {

    private final List<String> titles = new ArrayList<>();
    private final List<Fragment> fragments = new ArrayList<>();
    private String creditNo;
    private String orderId;
    private String from;

    @Override
    protected ServiceDetailsViewModel bindModel() {
        return getViewModel(this, ServiceDetailsViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initData() {
        initTitleBar(getString(R.string.service_detail));
        titles.add(getString(R.string.service_progress));
        titles.add(getString(R.string.service_intro));
        titles.add(getString(R.string.related_service));
        if (getIntent() != null) {
            String id = getIntent().getStringExtra(Constant.ID_KEY);
            String messageId = getIntent().getStringExtra(Constant.MESSAGE_ID_KEY);
            from = getIntent().getStringExtra(Constant.FROM_KEY);
            viewModel.getServiceDetails(id, messageId);
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initClick() {
        viewModel.detailsModelMutableLiveData.observe(this, serviceDetailsModel -> {
            if (serviceDetailsModel != null) {
                orderId = serviceDetailsModel.getOrderId();
                creditNo = serviceDetailsModel.getCreditNo();
                if (!TextUtils.isEmpty(serviceDetailsModel.getDeadline())) {
                    binding.includeService.serviceNameTv.setText(CommonUtil.checkText(serviceDetailsModel.getServiceName()) + context.getString(R.string.cycle_range, serviceDetailsModel.getDeadline()));
                } else {
                    binding.includeService.serviceNameTv.setText(CommonUtil.checkText(serviceDetailsModel.getServiceName()));
                }

                // 服务状态：0.待办 1.在办 2.暂停 3.已办结 4.已终止
                UiUtils.setServiceStatus(serviceDetailsModel.getStatus(), binding.includeService.serviceStatusTv, context);
                binding.includeService.rv.setLayoutManager(new FlowLayoutManager());
                AttrAdapter attrAdapter = new AttrAdapter();
                binding.includeService.rv.setAdapter(attrAdapter);
                attrAdapter.submitList(serviceDetailsModel.getServiceAttrList());
                binding.includeService.companyNameTv.setText(TextUtils.isEmpty(serviceDetailsModel.getEnterpriseName()) ? getString(R.string.no_company) : serviceDetailsModel.getEnterpriseName());
                binding.includeService.companyNextIv.setVisibility(TextUtils.isEmpty(serviceDetailsModel.getEnterpriseName()) ? View.GONE : View.VISIBLE);
                binding.includeService.companyDetailsLl.setEnabled(!TextUtils.isEmpty(serviceDetailsModel.getEnterpriseName()));
                binding.sourceOrderTv.setText(CommonUtil.checkText(serviceDetailsModel.getOrderNo()));
                binding.productNameTv.setText(CommonUtil.checkText(serviceDetailsModel.getProductName()));
                binding.orderTimeTv.setText(CommonUtil.checkText(serviceDetailsModel.getSubmitTime()));
                // 服务类型：0.交付 1.周期
                fragments.add(ServiceProgressFragment.newInstance(binding.viewPager, serviceDetailsModel.getServiceProgressList(), serviceDetailsModel.getCurrentPeriod(), serviceDetailsModel.getTotalPeriod(), serviceDetailsModel.getServiceType()));
                fragments.add(ServiceDescriptionFragment.newInstance(binding.viewPager, serviceDetailsModel.getInstruction()));
                fragments.add(CorrelationServiceFragment.newInstance(binding.viewPager, serviceDetailsModel.getRelServiceList()));
                ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), 0, titles, fragments);
                binding.viewPager.setAdapter(viewPagerAdapter);
                binding.tabLayout.setViewPager(binding.viewPager);
                binding.viewPager.setOffscreenPageLimit(3);
                binding.viewPager.setScrollable(false); // 禁止左右滑动
            }
        });
        viewModel.mErrorData.observe(this, ToastHelper::show);

        binding.includeService.companyDetailsLl.setOnClickListener(view -> {
            Bundle bundle = new Bundle();
            bundle.putString(Constant.CREDIT_NO_KEY, creditNo);
            JumpIntent.jump((Activity) context, CompanyDetailsActivity.class, bundle);
        });

        binding.sourceOrderLl.setOnClickListener(view -> {
            if (from.equals(Constant.orderList)) {
                finish();
                EventBus.getDefault().post(new EventBusModel(Constant.finishLookProgressDetailsPage));
            } else {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.ID_KEY, orderId);
                bundle.putString(Constant.FROM_KEY, from);
                JumpIntent.jump(this, OrderDetailsActivity.class, bundle);
            }
        });

        binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                // 重新计算的高度，比如切换tab页中的数据有的比较少的时候，也就是fragment中的view的高度小的时候，
                // ViewPager中的view的高度还是前面最大的那个高度，所以在它的下面会留下一段很长的空白。
                binding.viewPager.resetHeight(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (Constant.finishServiceDetailsPage.equals(eventBusModel.getMessage())) {
                finish();
            }
        }
    }
}